import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

import { CSS2DRenderer } from 'three/examples/jsm/renderers/CSS2DRenderer.js'
import { CSS3DRenderer } from 'three/examples/jsm/renderers/CSS3DRenderer.js'
import { createShadow } from '../utils/light.ts';

// 相机初始化位置
export const cameraPos = new THREE.Vector3(10, 6, 10);

export let scene: THREE.Scene, camera: THREE.PerspectiveCamera, renderer: THREE.WebGLRenderer, controls: OrbitControls,
    css3dRenderer: CSS3DRenderer, labelRenderer: CSS2DRenderer,
    controlsStartPos: THREE.Vector3 = new THREE.Vector3(),
    controlsMoveFlag: boolean = false, width: number, height: number

export const createScene = (canvas: HTMLCanvasElement, css3dDiv: HTMLDivElement, css2dDiv: HTMLDivElement) => {
    width = canvas.offsetWidth
    height = canvas.offsetHeight
    /** 场景 */
    scene = new THREE.Scene();
    scene.background = new THREE.Color('#000000');
    scene.fog = new THREE.Fog(new THREE.Color("rgba(111, 114, 130, 0.5)"), 8000, 12000)
    scene.add(new THREE.AxesHelper(10))
    /** 相机 */
    camera = new THREE.PerspectiveCamera(60, width / height, 0.2, 2000000);
    camera.position.copy(cameraPos);

    camera.layers.enableAll()

    // 渲染器
    renderer = new THREE.WebGLRenderer({
        canvas,
        precision: 'highp',
        antialias: true,
        powerPreference: 'high-performance',
        logarithmicDepthBuffer: true,
    });

    renderer.toneMappingExposure = 0.6
    
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(width, height);

    renderer.shadowMap.enabled = true;
    renderer.shadowMap.needsUpdate = true
    renderer.shadowMap.autoUpdate = true

    controls = new OrbitControls(camera, renderer.domElement);


    controls.addEventListener('start', () => {
        controlsStartPos.copy(camera.position)
    })


    controls.addEventListener('end', () => {
        controlsMoveFlag = controlsStartPos.distanceToSquared(camera.position) === 0
    })

    css3dRenderer = new CSS3DRenderer({
        element: css3dDiv
    });
    css3dRenderer.setSize(width, height);


    labelRenderer = new CSS2DRenderer({
        element: css2dDiv
    });

    labelRenderer.domElement.classList.add('css2d')

    labelRenderer.setSize(width, height);

    createShadow();


    controls.update()
    controls.addEventListener('change', () => {
        console.log(camera.position);
        
    })

    return {
        scene, camera, renderer, controls,
        css3dRenderer, labelRenderer
    }

}
